package logic

import (
	"context"
	"errors"
	"person/models/mysql"
	"person/pkg"

	"person/personrpc/internal/svc"
	"person/personrpc/personrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *personrpc.LoginRequest) (*personrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	user := &mysql.User{
		Account:  in.Account,
		Password: pkg.Md5(in.Password),
	}

	if err := user.FindUserByAccount(mysql.DB, in.Account); err != nil {
		return nil, errors.New("用户不存在")
	}

	if user.Password != pkg.Md5(in.Password) {
		return nil, errors.New("密码错误，请重新输入")
	}

	return &personrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
